package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.canton.buyer.BaseCantonFairBuyer;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import com.shlh.saas.service.canton.buyer.CantonFairBuyerService;
import com.shlh.saas.service.ExportRecordService;
import com.shlh.saas.util.FileUtils;
import com.shlh.saas.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 广交会采购商控制器
 */
@RestController
@RequestMapping("/purchasers")
@Slf4j
public class CantonFairPurchaserController {

    @Autowired
    private CantonFairBuyerService cantonFairBuyerService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private ExportRecordService exportRecordService;

    /**
     * 搜索广交会采购商数据（带分页）
     */
    @GetMapping("/canton-fair/search")
    public Result searchCantonFairPurchasers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String productType,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sessionInfo,
            @RequestParam(required = false) String country,
            @RequestParam(required = false) String hasContact
    ) {
        log.info("搜索广交会采购商数据，关键词：{}，产品类型：{}，页码：{}，每页数量：{}, 届数：{}, 国家：{}, 联系方式：{}",
                keyword, productType, page, size, sessionInfo, country, hasContact);
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            
            // 第一页不扣除额度，免费查看
            if (page == 1) {
                // 计算偏移量
                int offset = (page - 1) * size;
                
                // 获取分页数据
                List<BaseCantonFairBuyer> purchasers = cantonFairBuyerService.searchByKeywordInAllFields(
                    keyword, productType, offset, size, sessionInfo, country, hasContact);
                
                // 获取总记录数
                long total = cantonFairBuyerService.countByKeywordInAllFields(keyword, productType, sessionInfo, country, hasContact);
                
                // 增加搜索次数统计
                workbenchStatsService.incrementCantonBuyerSearchCount(userId);
                
                // 构造返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("records", purchasers);
                result.put("total", total);
                result.put("size", size);
                result.put("current", page);
                
                return Result.success(result);
            } else {
                // 检查用户余额
                UserBalance userBalance = userBalanceService.getByUserId(userId);
                if (userBalance == null || userBalance.getViewRecordsRemaining() < size) {
                    return Result.error("您的查看记录余额不足，请充值后再查看");
                }
                
                // 计算偏移量
                int offset = (page - 1) * size;
                
                // 获取分页数据
                List<BaseCantonFairBuyer> purchasers = cantonFairBuyerService.searchByKeywordInAllFields(
                    keyword, productType, offset, size, sessionInfo, country, hasContact);
                
                // 扣除用户查看记录余额
                userBalanceService.deductViewRecords(userId, purchasers.size());
                
                // 增加搜索次数统计
                workbenchStatsService.incrementCantonBuyerSearchCount(userId);
                
                // 获取总记录数
                long total = cantonFairBuyerService.countByKeywordInAllFields(keyword, productType, sessionInfo, country, hasContact);
                
                // 构造返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("records", purchasers);
                result.put("total", total);
                result.put("size", size);
                result.put("current", page);
                
                return Result.success(result);
            }
        } catch (Exception e) {
            log.error("搜索广交会采购商数据失败", e);
            return Result.error("搜索广交会采购商数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取符合条件的记录总数
     */
    @PostMapping("/canton-fair/count")
    public Result getCantonFairPurchasersCount(@RequestBody Map<String, Object> params) {
        String keyword = params != null && params.containsKey("keyword") ? (String) params.get("keyword") : null;
        String productType = params != null && params.containsKey("productType") ? (String) params.get("productType") : null;
        String sessionInfo = params != null && params.containsKey("sessionInfo") ? (String) params.get("sessionInfo") : null;
        String country = params != null && params.containsKey("country") ? (String) params.get("country") : null;
        String hasContact = params != null && params.containsKey("hasContact") ? (String) params.get("hasContact") : null;

        log.info("获取广交会采购商数据总数，关键词：{}，届数：{}，国家：{}，联系方式：{}", keyword, sessionInfo, country, hasContact);
        try {
            long count = cantonFairBuyerService.countByKeywordInAllFields(keyword, productType, sessionInfo, country, hasContact);
            
            // 限制最大返回数量为5万
            if (count > 50000) {
                count = 50000;
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取广交会采购商数据总数失败", e);
            return Result.error("获取广交会采购商数据总数失败: " + e.getMessage());
        }
    }

    /**
     * 导出广交会采购商数据
     */
    @PostMapping("/canton-fair/export")
    public void exportCantonFairPurchasers(
            HttpServletResponse response,
            @RequestBody(required = false) Map<String, Object> params,
            @RequestParam(required = true) Integer exportCount,
            @RequestParam(required = false) String selectedFields,
            @RequestParam(required = false, defaultValue = "zh") String language) {
        log.info("导出广交会采购商数据，参数: {}, 导出数量: {}, 选中字段: {}, 语言: {}", params, exportCount, selectedFields, language);
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getExportQuotaRemaining() < exportCount) {
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"您的导出次数余额不足，请充值后再导出\"}");
                return;
            }
            
            // 限制最大导出数量为5万
            if (exportCount > 50000) {
                exportCount = 50000;
            }
            
            // 提取过滤参数
            String keyword = params != null && params.containsKey("keyword") ? (String) params.get("keyword") : null;
            String productType = params != null && params.containsKey("productType") ? (String) params.get("productType") : null;
            String sessionInfo = params != null && params.containsKey("sessionInfo") ? (String) params.get("sessionInfo") : null;
            String country = params != null && params.containsKey("country") ? (String) params.get("country") : null;
            String hasContact = params != null && params.containsKey("hasContact") ? (String) params.get("hasContact") : null;

            log.info("导出广交会采购商数据，关键词：{}，届数：{}，国家：{}，联系方式：{}， 导出数量: {}",
                     keyword, sessionInfo, country, hasContact, exportCount);
            
            // 获取符合条件的数据（使用导出专用方法，返回完整敏感信息）
            List<BaseCantonFairBuyer> purchasers = cantonFairBuyerService.searchByKeywordInAllFieldsForExport(
                keyword, productType, 0, exportCount, sessionInfo, country, hasContact);

            log.info("导出专用：查询到符合条件的采购商数据: {} 条（不脱敏）", purchasers.size());
            
            if (purchasers.isEmpty()) {
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"没有找到符合条件的数据\"}");
                return;
            }
            
            // 扣除用户导出次数余额
            userBalanceService.deductExportQuota(userId, purchasers.size());
            
            // 增加导出次数统计
            workbenchStatsService.incrementCantonBuyerExportCount(userId, purchasers.size());

            // 处理字段选择（支持国际化）
            Map<String, String> fieldMapping = createFieldMapping(language);
            String[] selectedFieldArray;
            String[] selectedColumnNames;

            if (selectedFields != null && !selectedFields.trim().isEmpty()) {
                // 解析选中的字段
                String[] requestedFields = selectedFields.split(",");
                List<String> validFields = new ArrayList<>();
                List<String> validColumnNames = new ArrayList<>();

                for (String field : requestedFields) {
                    field = field.trim();
                    if (fieldMapping.containsKey(field)) {
                        validFields.add(field);
                        validColumnNames.add(fieldMapping.get(field));
                    } else {
                        log.warn("无效的字段名: {}", field);
                    }
                }

                if (validFields.isEmpty()) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.getWriter().write("{\"message\":\"没有有效的字段被选中，请至少选择一个有效字段\"}");
                    return;
                }

                selectedFieldArray = validFields.toArray(new String[0]);
                selectedColumnNames = validColumnNames.toArray(new String[0]);
                log.info("有效字段数量: {}, 字段列表: {}", validFields.size(), validFields);
            } else {
                // 如果没有指定字段，使用默认字段
                selectedFieldArray = getDefaultFields();
                selectedColumnNames = getDefaultColumnNames(language);
                log.info("使用默认字段进行导出");
            }

            // 自动确定标红字段（重要字段）
            String[] highlightFieldArray = getHighlightFields(selectedFieldArray);
            log.info("自动标红字段数量: {}, 标红字段列表: {}", highlightFieldArray.length, Arrays.toString(highlightFieldArray));

            // 设置导出文件名（支持国际化）
            String fileNamePrefix = "en".equals(language) ? "Canton_Fair_Purchasers_Data" : "广交会采购商数据";
            String fileName = fileNamePrefix + "_" + System.currentTimeMillis() + ".xlsx";
            
            // 获取当前时间戳作为文件名一部分
            String filePath = "/export/" + fileName;
            
            // 计算文件大小（以KB为单位）
            String fileSize = FileUtils.estimateExcelSize(purchasers.size()) + "KB";
            
            // 保存导出记录
            exportRecordService.addExportRecord(
                userId,
                fileName,
                "canton-fair-purchasers", // 数据来源
                fileSize,
                purchasers.size(),
                filePath
            );

            // 导出Excel（使用动态字段和自动标红样式）
            // 设置响应头，防止连接中断
            response.setHeader("Connection", "Keep-Alive");
            response.setHeader("Keep-Alive", "timeout=600");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 根据数据量选择不同的导出方法
            if (purchasers.size() > 10000) {
                log.info("数据量超过10000条，使用优化的导出方法");
                ExcelUtils.exportExcelWithHighlightOptimized(response, purchasers, "广交会采购商数据",
                        selectedColumnNames, selectedFieldArray, highlightFieldArray);
            } else {
                log.info("数据量不超过10000条，使用标准导出方法");
                ExcelUtils.exportExcelWithHighlight(response, purchasers, "广交会采购商数据",
                        selectedColumnNames, selectedFieldArray, highlightFieldArray);
            }
            
            log.info("成功导出广交会采购商数据，包含字段: {}，自动标红字段: {}",
                    Arrays.toString(selectedColumnNames), Arrays.toString(highlightFieldArray));
            
        } catch (Exception e) {
            log.error("导出广交会采购商数据失败", e);
            try {
                // 检查response是否已经提交
                if (!response.isCommitted()) {
                    response.reset();
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("{\"message\":\"导出数据失败: " + e.getMessage().replace("\"", "'") + "\"}");
                } else {
                    log.warn("响应已经提交，无法发送错误信息");
                }
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 查找采购商准确联系信息
     */
    @GetMapping("/canton-fair/contact")
    public Result getPurchaserFullContactInfo(@RequestParam(required = true) Long purchaserId, 
                                             @RequestParam(required = true) Integer sessionNumber,
                                             @RequestParam(required = true) String fieldName) {
        try {
            // 获取当前用户信息
            Long userId = UserContext.getUserId();
            log.info("{} 正在查找采购商准确联系信息，采购商ID: {}, 届数: {}, 字段名: {}", userId, purchaserId, sessionNumber, fieldName);
            
            // 检查用户是否有权限查看完整联系信息
            // 查询用户额度
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getViewRecordsRemaining() < 1) {
                return Result.error("您的查看记录余额不足，请充值后再查看");
            }
            
            // 获取完整联系信息
            String contactInfo = cantonFairBuyerService.getFullContactInfo(purchaserId, sessionNumber, fieldName);
            
            // 增加广交会采购商搜索次数统计
            workbenchStatsService.incrementCantonBuyerSearchCount(userId);

            // 扣除用户查看记录余额
            userBalanceService.deductViewRecords(userId, 1);
            
            // 创建返回数据结构，与前端期望的格式匹配
            Map<String, String> resultData = new HashMap<>();
            resultData.put(fieldName, contactInfo);
            
            return Result.success(resultData);
        } catch (Exception e) {
            log.error("获取采购商联系信息失败", e);
            return Result.error("获取采购商联系信息失败：" + e.getMessage());
        }
    }

    /**
     * 创建字段映射关系（支持国际化）
     * @param language 语言代码（zh/en）
     * @return 字段名到对应语言标题的映射
     */
    private Map<String, String> createFieldMapping(String language) {
        Map<String, String> fieldMapping = new HashMap<>();
        boolean isEnglish = "en".equals(language);

        // 直接属性字段
        fieldMapping.put("companyName", isEnglish ? "Company Name" : "公司名称");
        fieldMapping.put("country", isEnglish ? "Country/Region" : "国家/地区");
        fieldMapping.put("contactPerson", isEnglish ? "Contact Person" : "联系人");
        fieldMapping.put("phone", isEnglish ? "Phone" : "电话");
        fieldMapping.put("fax", isEnglish ? "Fax" : "传真");
        fieldMapping.put("address", isEnglish ? "Address" : "地址");
        fieldMapping.put("email", isEnglish ? "Email" : "电子邮箱");
        fieldMapping.put("website", isEnglish ? "Company Website" : "公司网站");
        // extendedFields中的字段，使用点号访问
        fieldMapping.put("extendedFields.sessionInfo", isEnglish ? "Canton Fair Session" : "广交会届数");
        fieldMapping.put("extendedFields.countryRegion", isEnglish ? "Country/Region (Extended)" : "国家/地区（扩展）");
        fieldMapping.put("extendedFields.procurementProductType", isEnglish ? "Procurement Product Type" : "采购产品类型");
        fieldMapping.put("extendedFields.contactTeam", isEnglish ? "Contact Team" : "联系团队");
        fieldMapping.put("extendedFields.contactWay", isEnglish ? "Contact Method" : "联系方式");
        fieldMapping.put("extendedFields.zipCode", isEnglish ? "Zip Code" : "邮编");
        return fieldMapping;
    }

    /**
     * 获取默认字段列表
     * @return 默认字段数组
     */
    private String[] getDefaultFields() {
        return new String[]{
            "companyName", "country", "extendedFields.procurementProductType", "contactPerson",
            "extendedFields.contactWay", "phone", "fax", "address", "extendedFields.zipCode",
            "email", "website", "extendedFields.sessionInfo"
        };
    }

    /**
     * 获取默认列名列表（支持国际化）
     * @param language 语言代码（zh/en）
     * @return 默认列名数组
     */
    private String[] getDefaultColumnNames(String language) {
        boolean isEnglish = "en".equals(language);
        if (isEnglish) {
            return new String[]{
                "Company Name", "Country/Region", "Procurement Product Type", "Contact Person", "Contact Method",
                "Phone", "Fax", "Address", "Zip Code", "Email", "Company Website", "Canton Fair Session"
            };
        } else {
            return new String[]{
                "公司名称", "国家/地区", "采购产品类型", "联系人", "联系方式",
                "电话", "传真", "地址", "邮编", "电子邮箱", "公司网站", "广交会届数"
            };
        }
    }

    /**
     * 获取需要标红的重要字段列表
     * @param selectedFields 用户选中的字段列表
     * @return 需要标红的字段数组（只包含用户选中的重要字段）
     */
    private String[] getHighlightFields(String[] selectedFields) {
        // 定义重要字段列表（需要标红的字段）
        String[] importantFields = {
            "companyName",                      // 公司名称
            "contactPerson",                    // 联系人
            "extendedFields.contactTeam",       // 联系团队
            "phone",                            // 电话
            "email",                            // 电子邮箱
            "website"                           // 公司网站
        };

        List<String> highlightFields = new ArrayList<>();
        Set<String> selectedFieldSet = new HashSet<>(Arrays.asList(selectedFields));

        // 只有当重要字段被用户选中时，才加入标红列表
        for (String importantField : importantFields) {
            if (selectedFieldSet.contains(importantField)) {
                highlightFields.add(importantField);
            }
        }

        return highlightFields.toArray(new String[0]);
    }
}